import {useEffect, useState} from "react";
import {LoginOutlined} from "@ant-design/icons";
import {Button, Col, Form, Input, Layout, message} from "antd";
import Card from "antd/es/card";
import Row from "antd/es/grid/row";
import {getColorPrimary, getRes} from "../../utils/constants";
import axios from "axios";
import {useNavigate} from "react-router-dom";
import Title from "antd/es/typography/Title";
import {ssData} from "../../index";
import PWAHandler from "../../PWAHandler";
import {removeAllCaches} from "../../cache";

const md5 = require("md5");

const layout = {
    labelCol: {span: 8},
    wrapperCol: {span: 8},
};

const {Content, Footer} = Layout;

type LoginState = {
    userName: string;
    password: string;
};

const Index = ({offline}: { offline: boolean }) => {
    const [logging, setLogging] = useState<boolean>(false);
    const [loginState, setLoginState] = useState<LoginState>({
        userName: "",
        password: "",
    });

    const [messageApi, contextHolder] = message.useMessage({maxCount: 3});

    const navigate = useNavigate();

    const setValue = (value: LoginState) => {
        setLoginState(value);
    };

    const onFinish = async (allValues: any) => {
        setLogging(true);
        const loginForm = {
            userName: allValues.userName,
            password: md5(allValues.password),
            https: window.location.protocol === "https:",
        };
        try {
            const {data} = await axios.post("/api/admin/login", loginForm);
            if (data.error) {
                await messageApi.error(data.message);
            } else if (data.error == 0) {
                const query = new URLSearchParams(window.location.search);
                if (ssData) {
                    ssData.key = data.data.key;
                }
                const redirectFrom = query.get("redirectFrom") as string;
                if (redirectFrom !== null && redirectFrom !== "") {
                    const jumpTo = decodeURIComponent(redirectFrom);
                    //处理非 https iframe 跳转登录问题
                    if (jumpTo.startsWith("/admin/plugins/")) {
                        window.location.href = window.location.protocol + "//" + window.location.host + jumpTo;
                    } else {
                        navigate(jumpTo.replace("/admin", ""), {replace: true});
                    }
                } else {
                    navigate("/index", {replace: true});
                }
            } else {
                await messageApi.error("未知错误");
            }
        } finally {
            setLogging(false);
        }
    };

    useEffect(() => {
        removeAllCaches();
    }, []);

    return (
        <PWAHandler>
            {contextHolder}
            <Layout style={{height: "100vh"}}>
                <Content
                    style={{
                        minWidth: "100%",
                        display: "flex",
                        alignItems: "center",
                        paddingRight: 24,
                        paddingLeft: 24,
                    }}
                >
                    <Card
                        cover={
                            <div style={{textAlign: "center"}}>
                                <img
                                    alt={"bg"}
                                    src={``}
                                    style={{
                                        objectFit: "cover",
                                        opacity: 0.6,
                                        filter: "alpha(opacity=60)",
                                        width: "100%",
                                        position: "relative",
                                        display: "flex",
                                        flexDirection: "column",
                                        borderRadius: "8px 8px 0 0",
                                        alignItems: "center",
                                        textAlign: "center",
                                        backgroundSize: "cover",
                                        height: "120px",
                                    }}
                                />
                                <Title level={3} style={{color: "#fff", background: getColorPrimary(), margin: 0}}>
                                    {getRes()["userNameAndPassword"]}
                                </Title>
                            </div>
                        }
                        style={{
                            textAlign: "center",
                            width: "100%",
                            marginRight: "auto",
                            marginLeft: "auto",
                            maxWidth: "660px",
                        }}
                        styles={{
                            body: {
                                margin: 16,
                            },
                        }}
                    >
                        <Form
                            {...layout}
                            initialValues={getRes().defaultLoginInfo}
                            onFinish={(values) => onFinish(values)}
                            onValuesChange={(_k, v) => setValue(v)}
                        >
                            <Form.Item label={getRes().userName} name="userName" rules={[{required: true}]}>
                                <Input value={loginState.userName}/>
                            </Form.Item>

                            <Form.Item label={getRes().password} name="password" rules={[{required: true}]}>
                                <Input.Password value={loginState.password}/>
                            </Form.Item>

                            <Row style={{alignItems: "center", display: "flex"}}>
                                <Col xxl={24} xs={24}>
                                    <Button disabled={offline} loading={logging} type="primary" htmlType="submit">
                                        <LoginOutlined/> {getRes().login}
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                </Content>
                <Footer style={{textAlign: "center"}}>
                    {getRes().copyrightCurrentYear} {getRes().websiteTitle}. All Rights Reserved.
                </Footer>
            </Layout>
        </PWAHandler>
    );
};

export default Index;
